package cn.xval.ft.core.marketdata.manage.method;

import cn.xval.ft.core.ctp.CThostFtdcReqUserLoginField;
import cn.xval.ft.core.ctp.CThostFtdcRspInfoField;
import cn.xval.ft.core.ctp.CThostFtdcRspUserLoginField;
import cn.xval.ft.core.marketdata.manage.MarketDataSpi;
import cn.xval.ft.core.marketdata.manage.SpiManager;
import cn.xval.ft.core.marketdata.manage.SpiStatus;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Login {
    private MarketDataSpi spi;

    public Login(MarketDataSpi spi) {
        this.spi = spi;
    }

    public void doLogin() {
        var info = spi.getInfo();
        log.info("使用账号{}登录", info.getUserId());
        CThostFtdcReqUserLoginField req = new CThostFtdcReqUserLoginField();
        req.setBrokerID(info.getBrokerId());
        req.setUserID(info.getUserId());
        req.setPassword(info.getPassword());
        spi.setCurrentStatus(SpiStatus.login);
        spi.getConnect().ReqUserLogin(req, SpiManager.nextRequestId());
    }

    public boolean onRspUserLogin(CThostFtdcRspUserLoginField pRspUserLogin, CThostFtdcRspInfoField pRspInfo, int nRequestID, boolean bIsLast) {
        var bSuccess = pRspInfo != null && pRspInfo.getErrorID() == 0;
        if (bSuccess) {
            // 登陆成功
            spi.setCurrentStatus(SpiStatus.loginOk);
//            this.tradingDay = pRspUserLogin.getTradingDay();
            log.info("登录成功,交易日:{}", pRspUserLogin.getTradingDay());
            // 通知管理者，登录成功
            SpiManager.connectActive(spi.getId());
            return true;
            // 订阅行情
//            log.info("订阅行情");
//            api.SubscribeMarketData(instruments, instruments.length);
        }
        else if (pRspInfo != null) {
            spi.setCurrentStatus(SpiStatus.loginFailedByLogic)
                    .setExtra("%d: %s".formatted(pRspInfo.getErrorID(), pRspInfo.getErrorMsg()));
            log.error("登录失败 -> id: {}, message: {}", pRspInfo.getErrorID(), pRspInfo.getErrorMsg());
        }
        else {
            spi.setCurrentStatus(SpiStatus.loginFailedByNet);
            log.error("登录失败 -> 未知错误");
        }
        return false;
    }
}
